package com.hontech.bvapp2.service

import android.os.Environment
import com.hontech.bvapp2.utils.AppTask
import com.hontech.bvapp2.utils.runIO
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.Calendar
import java.util.Date

@Serializable
data class TbFirmFile (
    val id: Long,
    val name: String,
    val description: String,
    val version: String,
    val size: Long,
    @SerialName("create_timestamp")
    val createTimestamp: Long,
) {

    fun dateFormat(): String {
        val date = Date(createTimestamp * 1000)
        val calendar = Calendar.getInstance()
        calendar.time = date
        return "${calendar.get(Calendar.YEAR)}-${calendar.get(Calendar.MONTH) + 1}-${calendar.get(
            Calendar.DAY_OF_MONTH)} ${calendar.get(Calendar.HOUR_OF_DAY)}:${calendar.get(Calendar.MINUTE)}:${calendar.get(
            Calendar.SECOND)}"
    }
}

object FirmFile {

    suspend fun query(typeId: Long) = runIO {
        Http.get("/api/firm_file/query?type_id=$typeId").parse<Array<TbFirmFile>>()
    }

    suspend fun downloadBin(id: Long) = runIO {
        val resp = Http.get("/api/firm_file/download?id=$id")
        resp.body?.bytes() ?: throw IllegalStateException("no body")
    }

    suspend fun downloadApk(id: Long, cb: (Long) -> Unit) = runIO {
        val resp = Http.get("/api/firm_file/download?id=$id")
        val file = File(Environment.getExternalStorageDirectory(), "client.apk")
        if (!file.exists()) {
            file.createNewFile()
        }
        val out = FileOutputStream(file)
        val body = resp.body ?: throw IOException("网络错误")
        val size = body.contentLength()
        val input = body.byteStream()
        input.use {
            out.use {
                val buf = ByteArray(1024 * 10)
                var index = 0L
                while (index < size) {

                    val n = input.read(buf)
                    if (n <= 0) {
                        throw IOException("recv fail")
                    }
                    out.write(buf, 0, n)
                    index += n
                    AppTask.post { cb(index * 100 / size) }
                }
            }
        }
        file.path
    }
}











